package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;



public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    //这个操作会绑定端口号
    public TcpEchoServer(int port) throws IOException {
        serverSocket  = new ServerSocket(port);


    }
    public void start() throws IOException {
        System.out.println("启动服务器！");
        while(true){
        Socket clientSocket = serverSocket.accept();
            Thread t = new Thread(()->{
                processConnection(clientSocket);
            });
                t.start();
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d]客户端上线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //接下来读取请求，根据请求计算响应，返回响应
        //Socket对象内部包含了
        try ( InputStream inputStream = clientSocket.getInputStream();
              OutputStream outputStream = clientSocket.getOutputStream();){
            while(true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s,%d] 客户端下线！",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();//刷新

                System.out.printf("[%s:%d] req: %s,  resq: %s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),
                        request,response);
            }

        }catch(IOException e){
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
